package com.imay.live.fragment.dynamics;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.imay.base.helper.NetworkHelper;
import com.imay.base.util.RecyclerViewUtil;
import com.imay.live.activity.discovery.TopicDynamicActivity;
import com.imay.live.fragment.BaseRequestFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.view.LoadView;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;


/**
 * 线性以及格子动态公共布局
 * Created by chan on 2017/4/21.
 */

public abstract class DynamicsBaseFragment extends BaseRequestFragment {

    protected TwinklingRefreshLayout mRefreshLayout;
    protected RecyclerView mRecyclerView;

    private String likeCreateRequest;
    private String likeDelRequest;

    protected boolean isLoading = false;
    protected boolean isEnd = false;
    protected boolean mIsRefreshing = false;

    protected LoadView loadView;

    public TwinklingRefreshLayout getmRefreshLayout() {
        return mRefreshLayout;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadView = new LoadView(getContext());
        loadView.setVisibility(View.INVISIBLE);
    }

    /**
     * 公共方法构造上拉下拉事件
     */
    protected void initListener() {
        loadView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getParentFragment() instanceof DynamicsFragment) {
                    ((DynamicsFragment) (getParentFragment())).refreshData();
                } else if (getActivity() instanceof TopicDynamicActivity) {
                    ((TopicDynamicActivity) getActivity()).onRefresh();
                }
            }
        });

        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                if (!isLoading) {
                    mHandler.obtainMessage(0).sendToTarget();
                } else {
                    mRefreshLayout.finishRefreshing();
                }
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                if (!mIsRefreshing) {
                    mHandler.obtainMessage(1).sendToTarget();
                } else {
                    mRefreshLayout.finishLoadmore();
                }
            }
        });

        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    /**
     * 刷新回调
     */
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            mIsRefreshing = true;
            super.dispatchMessage(msg);
            if (msg.what == 0) {
                if (getParentFragment() instanceof DynamicsFragment) {
                    ((DynamicsFragment) (getParentFragment())).refreshData();
                } else if (getActivity() instanceof TopicDynamicActivity) {
                    ((TopicDynamicActivity) getActivity()).onRefresh();
                } else if (getActivity() instanceof DynamicsListener) {
                    ((DynamicsListener) getActivity()).refreshData();
                }
            } else if (msg.what == 1) {
                if (getParentFragment() instanceof DynamicsFragment) {
                    ((DynamicsFragment) (getParentFragment())).loadMore();
                } else if (getActivity() instanceof TopicDynamicActivity) {
                    ((TopicDynamicActivity) getActivity()).onLoadMore();
                } else if (getActivity() instanceof DynamicsListener) {
                    ((DynamicsListener) getActivity()).loadMore();
                }
            }
        }
    };

    protected void refresh() {

    }

    /**
     * CoolLayout与refresh冲突
     *
     * @param springViewEnable
     */
    @Override
    public void setSpringViewEnable(boolean springViewEnable) {
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnableRefresh(springViewEnable);
        }
    }

    /**
     * 点赞
     */
    protected void likeCreate(int feedId) {
        if (!NetworkHelper.getInstance().hasConnection()) {
            DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
            ErrorResult.toastError(getContext(), ResultCode.CodeNetErrorAction);
            return;
        }
        likeCreateRequest = ProtoRequestHelper.task(ProtoHttpFactory.likeCreate(feedId)).setTag(this.hashCode()).request(this);
    }

    protected void likeDel(int feedId) {
        if (!NetworkHelper.getInstance().hasConnection()) {
            DialogFragmentHelper.closeLoadingDialog(getChildFragmentManager());
            ErrorResult.toastError(getContext(), ResultCode.CodeNetErrorAction);
            return;
        }
        likeDelRequest = ProtoRequestHelper.task(ProtoHttpFactory.likeDel(feedId)).setTag(this.hashCode()).request(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }


    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(likeCreateRequest)) { // 点赞
            //EventHelper.postDynamicsUpdate(); // 动态信息改变
        } else if (command.equals(likeDelRequest)) { // 取消赞
            //EventHelper.postDynamicsUpdate(); // 动态信息改变
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        ErrorResult.toastError(getActivity(), code);
    }

    public void loadError(String string) {
        mRecyclerView.setVisibility(View.INVISIBLE);
        loadView.loadError(string);
    }

    public void scrolltoTop() {
        RecyclerViewUtil.smoothScrollToTopWithRefresh(mRecyclerView, mRefreshLayout);
    }
}
